package servlet;

import Dao.UserDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/loginServlet2")
public class LoginServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter writer = response.getWriter();
        Map map=new HashMap();
        //1.获取用户输入
        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        if(userName!=null && password!=null) {
            //2.创建对象
            User u=new User(userName,password);
            //3.验证密码
            UserDao userDao=new UserDao();
            //boolean result=userDao.checkLogin(u);
            String result=userDao.checkLogin(u);
            if(result!="") {
                //1.把用户信息保存到session中
                request.getSession().setAttribute("user",u);

                //2.创建cookie，设置存活期限
                String autologin=request.getParameter("autoLogin");
                if(autologin!=null){
                    Cookie cookie=new Cookie("autoLogin",userName+"-"+password);
                    //设置cookie的最大存活期
                    System.out.println(Integer.parseInt(autologin));
                    System.out.println(autologin);
                    cookie.setMaxAge(Integer.parseInt(autologin));
                    //设置cookie的路径
                    cookie.setPath(request.getContextPath());
                    response.addCookie(cookie);
                }


                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;");
                response.setCharacterEncoding("utf-8");

                response.sendRedirect("main.html?stuNo="+result);
//                request.getRequestDispatcher("main.html").forward(request,response);
//                request.getRequestDispatcher("test.jsp").forward(request,response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
